package com.compomics.proteocloud.db;

import java.io.IOException;
import java.net.ConnectException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;

import com.compomics.proteocloud.util.AWSUtils;
import org.jets3t.service.security.AWSCredentials;

/**
 * This class manages the setting up of the database system.
 * User: Thilo Muth
 * Date: 03.09.2010
 * Time: 14:43:35
 * 
 */
public class DBManager {

    private Connection connection;
	private Properties props;
	private static String JDBCDRIVER = "com.mysql.jdbc.Driver";
    private static String URL_1 = "jdbc:mysql://";
    private static String URL_2 = ":3306/";
    private String dbName;
    /**
     * Constructor of the DBManager.
     * @param awsCredentials
     * @throws SQLException 
     */
    public DBManager(AWSCredentials awsCredentials, String dbName) throws SQLException, ConnectException {
    	props = AWSUtils.getProperties();
    	this.dbName = dbName;
        initConnection();
    }
    
    /**
     * Initializes the database connection.
     */
    private void initConnection() throws ConnectException {
         // Get a connection to the database
        try {
            // Register the JDBC driver for MySQL
            Class.forName(JDBCDRIVER);
            
            // Do the connection to the DB
            if(props.getProperty(AWSUtils.DATABASE_URL).length() == 0) {
                throw new ConnectException("No valid database URL specified!");
            } else if (props.getProperty(AWSUtils.DATABASE_URL).length() == 0) {
                throw new ConnectException("No valid database user specified!");
            } else if(props.getProperty(AWSUtils.DATABASE_PASS).length() == 0) {
                throw new ConnectException("No valid database password specified!");
            } else {
                connection = DriverManager.getConnection(URL_1 + props.getProperty(AWSUtils.DATABASE_URL) + URL_2 + dbName, props.getProperty(AWSUtils.DATABASE_USER), props.getProperty(AWSUtils.DATABASE_PASS));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException ex) {
            ex.printStackTrace();
        }
    }
    
    /**
     * Returns the connection.
     * @return connection Connection instance
     */
    public Connection getConnection() {
        return connection;
    }
}